<?php

namespace app\admin\jobs;

use app\admin\model\Images as ImagesModel;
use app\admin\model\MarketSmCopywriting as MarketSMCopywritingModel;
use app\admin\model\SystemConfig;
use app\common\ApiClient;
use app\common\RabbitMQClient;
use think\facade\Config;
use think\facade\Db;
use think\Exception;
use GuzzleHttp;

class MarketSMCopywritingPublish
{
    /**
     * 发布社媒文案到社媒平台 具体实现
     * @param $data
     * @return bool
     */
    public function execute()
    {

        $callback = function ($msg) {
            $data = $msg;

            if ($data) {
                $data = json_decode($data, true);
                if (isset($data['id']) && $data['id']) {

                    $env = env('APP_ENV') ?? 'dev';
                    $domain = Config::get('domain')[$env]['facebookAutoPublishing'];

                    // 查询数据
                    $channelDataTwoDimensional = Db::name('system_sm_channel')
                        ->where(['status' => 1, 'is_del' => 0])
                        ->field('id,name')
                        ->select()
                        ->toArray();

                    $channelData = array_column($channelDataTwoDimensional, 'name', 'id');

                    $oMarketSMCopywritingData = MarketSMCopywritingModel::with(['account', 'task'])->find($data['id']);
                    if(!$oMarketSMCopywritingData || !$oMarketSMCopywritingData->task){
                        return true;// 移除队列
                    }

                    $imgs_arr = [];
                    if ($oMarketSMCopywritingData && $oMarketSMCopywritingData->task && $oMarketSMCopywritingData->task->imgs) {
                        $img_arr = explode(',', $oMarketSMCopywritingData->task->imgs);
                        $oImages = new ImagesModel();
                        $imgs_arr = $oImages->getImagesByIds($img_arr);
                    }

                    $postData = [
                        'ads_id' => $oMarketSMCopywritingData->windows_id,
                        'platform' => isset($channelData[$oMarketSMCopywritingData->task->channel_id]) ? $channelData[$oMarketSMCopywritingData->task->channel_id] : '',
                        'text_prompt' => $oMarketSMCopywritingData->content,
                        'image_url' => $imgs_arr ? reset($imgs_arr)['url'] : '',
                    ];

                    try {
                        $apiClient = new ApiClient($domain);
                        $result = $apiClient->post('/api/post', ['body' => json_encode($postData)]);

                        // 检查 result 结果，如果 code 为 200 则确认消息已处理
                        if (isset($result['code']) && $result['code'] === 200 && isset($result['data']['user_url'])) {
                            $oMarketSMCopywritingData->publish_status = 3;
                            $oMarketSMCopywritingData->publish_url = $result['data']['user_url'];
                            $oMarketSMCopywritingData->save();
                        } else {
                            $oMarketSMCopywritingData->publish_status = 4;
                            $oMarketSMCopywritingData->publish_results = $result['message'];
                            // 如果次数超过3次 次数归0 跳出队列
                            if($oMarketSMCopywritingData->retry_num >= 3){
                                $oMarketSMCopywritingData->retry_num = 0;
                                $oMarketSMCopywritingData->save();
                            }else{
                                $oMarketSMCopywritingData->retry_num += 1;
                                $oMarketSMCopywritingData->save();
                                throw new Exception($result['message']);
                            }
                        }

                    } catch (Exception $e) {
                        return false;
                    } catch (GuzzleHttp\Exception\RequestException $e) {
                        error_log('请求超时或网络错误:' . $e->getMessage());
                        return false;
                    }
                    return true;
                }
            }
            return false;
        };

        // 确保 durable 参数为 true，以保证消息持久化
        $rabbitMQService = new RabbitMQClient();
        $rabbitMQService->receiveMessage('newsPublish', $callback);
        $rabbitMQService->close();
    }
}
